package com.m3839.sdk.login.ui.controller;

import android.app.Activity;
import android.app.FragmentManager;

import com.m3839.sdk.common.base.UIStackManager;
import com.m3839.sdk.common.core.Constant;
import com.m3839.sdk.common.util.AppUtils;
import com.m3839.sdk.login.bean.InternalTip;
import com.m3839.sdk.login.ui.LoginHostFragment;
import com.m3839.sdk.login.ui.LoginTipDialogFragment;
import com.m3839.sdk.login.ui.LoginWebFragment;

/**
 * @author ChenBaoyang
 * @description: LoginUiControllerImpl
 * @date 2021/12/8 15:18
 */
public class LoginUiControllerImpl implements ILoginUiController {

    @Override
    public void showWebLoginDialog(Activity activity) {
        if (UIStackManager.getInstance().hasFragment(Constant.HYKB_TAG_FRAGMENT_LOGIN_WEB)) {
            return;
        }
        LoginWebFragment.newInstance().show(activity.getFragmentManager(),
                Constant.HYKB_TAG_FRAGMENT_LOGIN_WEB);
    }

    @Override
    public void showLoginTipDialog(Activity activity, InternalTip tip) {
        LoginTipDialogFragment dialogFragment = (LoginTipDialogFragment) UIStackManager.getInstance()
                .getFragment(Constant.HYKB_TAG_FRAGMENT_TIP_BANNED);

        if (dialogFragment != null) {
            dialogFragment.update(tip);
        } else {
            dialogFragment = LoginTipDialogFragment.newInstance(tip);
            dialogFragment.show(activity.getFragmentManager(), Constant.HYKB_TAG_FRAGMENT_TIP_BANNED);
        }
    }

    @Override
    public void callLoginHostPage(Activity activity) {
        if (AppUtils.checkVersionCode(activity, Constant.HYKB_PACKAGE_NAME,
                Constant.HYKB_SUPPORT_LOW_VERSION)) {
            //满足条件，开启透明层，调用快爆app的登录
            FragmentManager fm = activity.getFragmentManager();
            LoginHostFragment current = (LoginHostFragment) fm.findFragmentByTag(
                    Constant.HYKB_TAG_FRAGMENT_LOGIN);
            if (current == null) {
                current = new LoginHostFragment();
                fm.beginTransaction()
                        .add(current, Constant.HYKB_TAG_FRAGMENT_LOGIN)
                        .commitAllowingStateLoss();
            } else {
                current.getUserInfoFromHykbApp();
            }
        } else {
            showWebLoginDialog(activity);
        }
    }

    @Override
    public void dismissAllLoginDialog() {
        UIStackManager.getInstance().finishFragment(Constant.HYKB_TAG_FRAGMENT_TIP_BANNED);
        UIStackManager.getInstance().finishFragment(Constant.HYKB_TAG_FRAGMENT_LOGIN_WEB);
    }
}
